﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.Persistent;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule.InStoreDataMeasures;
using Jumpton.Persistent;
using Jumpton.SFA.Entity;



public partial class masterdata_Product_detail : PageBase
{

    ObjectTable ot;
    private PRODUCTS product;
    private static int id = 0;
    private const string ProductID = "id";
    private const string RESPONSE_PRODUCT_LIST = "Product_List.aspx";
    private const string RESPONSE_PRODUCT_UOM_MAITAIN = "Product_UOM_Maintain.aspx?productID=";
    static decimal count = -1, start_record = 0, end_record = 10, pages = 0, pagesize = 12, curpage = 1;


    protected void Page_Load(object sender, EventArgs e)
    {
        id = -1;
        int.TryParse(Request.QueryString[ProductID], out id);
        if (!IsPostBack)
        {
            InitForm();
            FillForm();
            String SelectedValue  = null;
            if (product != null)
            {
                SelectedValue = product.FORMCODE;
            }
            //挂接系列树
            var dt = FormManager.GetFormTree(MyStateManager.DomainID);
            if (dt != null && dt.Rows.Count > 0)
            {
                String LastCode = null;
                foreach (DataRow row in dt.Rows)
                {
                    String Code = row["MCODE"].ToString();
                    if (LastCode != Code)
                    {
                        TreeNode node = new TreeNode(row["MNAME"].ToString() + "[制造商]", row["MCODE"].ToString());
                        this.TreeForms.BuildTree(node, dt, "MCODE", node.Value, "CCODE", "CNAME", SelectedValue);
                        TreeForms.Nodes.Add(node);
                        LastCode = Code;
                    }

                }
            }
            BindPhoto();
            btnQuery_Click(sender, e);
        }
    }


    protected void btnQuery_Click(object sender, EventArgs e)
    {
        String where = null;
        if (drpPhotoType.SelectedIndex != 0)
        {
            where = " AND PHOTO_TYPE_ID=" + drpPhotoType.SelectedValue;
        }
        count = PhotoManager.Count(MyStateManager.DomainID, where);
        ViewState["where"] = where;
        if (count > 0)
        {

            pages = Math.Ceiling(count / pagesize);//总页数
            start_record = 1;
            end_record = pagesize;
            curpage = 1;
            txtInfo.Text = string.Format("总共<font color=blue>{0}</font>条记录&nbsp;&nbsp;共{1}页&nbsp;&nbsp;当前第{2}页", count, pages, curpage);

        }
        else
        {
            start_record = 0;
            end_record = 0;
            pages = 0;
            curpage = 0;
            txtInfo.Text = string.Format("总共<font color=blue>{0}</font>条记录&nbsp;&nbsp;共{1}页&nbsp;&nbsp;当前第{2}页", 0, 0, 0);
        }
        BindFrom(start_record, end_record);

    }
    
    private void FillForm()
    {
        if (id >= 0)
        {
            ProductManager manager = new ProductManager();
            product = manager.Load(id);

            if (product != null)
            {
                txtCode.Value = product.ProductCode;
                txtName.Value = product.ProductName;
                txtShortName.Value = product.ShortProductName;
                txtPiecePrice.Text = product.PIECE_PRICE.ToString();
                chkYesNo.Checked = product.ACTIVE;
                txtRemark.Text = product.ADDITIONALINFO;
                txtSort.Value = product.SEQUENCE.ToString();
                try
                {
                    txtCasePrice.Value = product.CasePrice.ToString();
                }
                catch
                {

                }

                PRODUCT_UOMS productUOM = Product_UomsManager.GetProductUom(MyStateManager.DomainID, id);
                if (productUOM != null)
                {
                    txtCSName.Text = productUOM.CSNAME;
                    txtDefaultUOM.Text = productUOM.PCNAME;
                    txtNum.Text = productUOM.DENOMINATOR.ToString();
                    hfProductUOM.Value = productUOM.ID.ToString();
                }
            }

        }
    }

    private void InitForm()
    {
        var ot = new DictionaryItemsManager().GetItemList(DictionaryEnum.PhotoType, MyStateManager.DomainID);
        drpPhotoType.DataSource = ot;
        drpPhotoType.DataBind();
        drpPhotoType.Items.Insert(0, new ListItem("全部", ""));
    }

 
    #region 绑定税率
    //public void GetTaxesType()
    //{
    //    ddlTaxes.DataTextField = "DESCRIPTION";
    //    ddlTaxes.DataValueField = "ID";
    //    ot = TaxesManager.GetTaxesTable(MyStateManager.DomainID);
    //    if (ot != null)
    //    {
    //        ot.BillDataTable.DefaultView.RowFilter = "VALID='1'";
    //        ddlTaxes.DataSource = ot.BillDataTable.DefaultView;
    //        ddlTaxes.DataBind();
    //    }
    //    ddlTaxes.Items.Insert(0, new ListItem("-选择税率-", ""));
    //}
    #endregion



    protected void setText(object sender, EventArgs e)
    {
        try
        {
            txtCasePrice.Value = (float.Parse(txtPiecePrice.Text) * int.Parse(txtNum.Text)).ToString();
        }
        catch (Exception err)
        {
            
        }
    }
    protected void btnUoms_Click(object sender, EventArgs e)
    {
        try
        {
            SaveData();
            Response.Redirect(RESPONSE_PRODUCT_UOM_MAITAIN + (id.ToString()));
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!IsValid)
            return;

        if (TreeForms.SelectedNode == null)
        {
            ShowMessage("请选择一个商品系列");
            return;
        }
        try
        {
         
            if (this.SaveData())
            {
                ShowMessage("保存成功", RESPONSE_PRODUCT_LIST);
            }else
                ShowMessage("保存失败");
        }
           
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
       

    }

    private bool SaveData()
    {
        try
        {
         
            long time=long.Parse(Jumpton.SFA.Server.BusinessRule.BusinessLogic.GetDateTimeString(DateTime.Now));
            PRODUCTS product = null;
            PRODUCT_UOMS productUOM = new PRODUCT_UOMS();
            productUOM.CREATETIME = time;
            ProductManager manager = new ProductManager();
            Product_UomsManager uomManager = new Product_UomsManager();
            productUOM.UomsCode = "CS";

            if (id <= 0)
            {
                product = new PRODUCTS();
                product.CREATETIME = time;
                product.ProductName = txtName.Value;
                product.PINYINNAME = Pinyin.GetStringToPinYin(product.ProductName);
            }
            else
            {
                product = manager.Load(id);
                if (hfProductUOM.Value != string.Empty)
                {
                    productUOM = uomManager.Load(int.Parse(hfProductUOM.Value));
                }
                if (product.ProductName != txtName.Value || string.IsNullOrEmpty(product.PINYINNAME))
                {
                   
                    product.PINYINNAME = Pinyin.GetStringToPinYin(product.ProductName);
                }
                product.ProductName = txtName.Value;
              
            }

            product.ProductCode = txtCode.Value;
          
            product.ShortProductName = txtShortName.Value;

            product.CategoryCode = TreeForms.SelectedNode.Parent.Parent.Value;
            product.BrandCode = TreeForms.SelectedNode.Parent.Value;
            product.FORMCODE = TreeForms.SelectedNode.Value;
            product.ManuCode = TreeForms.SelectedNode.Parent.Parent.Parent.Value;
            product.SEQUENCE = int.Parse(txtSort.Value==""?"0":txtSort.Value);
            if (!string.IsNullOrEmpty(txtPiecePrice.Text))
            {
                product.PIECE_PRICE = Decimal.Parse(txtPiecePrice.Text);
            }
            product.BASEUOMCODE = "PC";
            product.ACTIVE = chkYesNo.Checked;
            product.DOMAINID = MyStateManager.DomainID;
            product.LAST_UPDATER = MyStateManager.UserID.ToString();
            product.LAST_UPDATE_TIME = time;
            product.ADDITIONALINFO = txtRemark.Text;
            if (txtCasePrice.Value != string.Empty)
            {
                product.CasePrice = decimal.Parse(txtCasePrice.Value);
            }

            bool Successful = false;
            Successful = manager.Save(product);
            productUOM.DENOMINATOR = txtNum.Text == string.Empty ? 0 : decimal.Parse(txtNum.Text);
            productUOM.LAST_UPDATE_TIME = time;
            productUOM.LAST_UPDATER = MyStateManager.UserID.ToString();
            productUOM.DOMAINID = MyStateManager.DomainID;
            productUOM.PRODUCTID = id<=0?manager.Load(product.ProductCode, product.DOMAINID, product.ID).ID:id;
            productUOM.ACTIVE =true;
            productUOM.PCNAME = txtDefaultUOM.Text;
            productUOM.CSNAME = txtCSName.Text;
            productUOM.UomsCode = "PC";
            id = (int)productUOM.PRODUCTID;
            productUOM.SELLFLAG = "1";
            string LogContent = "";

            if (product.State==DataRowState.Added)
            {
                LogContent += "增加新的产品" + txtCode.Value + "，它的信息是：";
            }
            else
            {
                LogContent += product.ProductCode + "信息发生变动，变动后信息是：";
            }
            LogContent += "产品编号：" + product.ProductCode + "，";
            LogContent += "产品名称：" + product.ProductName + "，";
            LogContent += "产品简称：" + product.ShortProductName + "，";

            LogContent += "包（价）：" + product.CasePrice + "，";
            LogContent += "件（价）：" + product.PIECE_PRICE + "，";
            LogContent += "规格转换 1件=：" + productUOM.DENOMINATOR + "，";
            //LogContent += "件体积(M3)：" + productUOM.VOLUME + "，";
            //LogContent += "件重量(KG)：" + productUOM.WEIGHT + "，";
            LogContent += "备注：" + product.ADDITIONALINFO + "，";
       //     LogContent += "规格转换 1自然件=：" + txtStandardPrice.Text + "，";
            LogContent += "有效：" + product.ACTIVE + "，";
            LogContent += "箱是否出售：" + productUOM.SELLFLAG + "，";
            LogContent += "促销标志：" + product.PROMOFLAG + "，";
            LogContent += "操作人：" + productUOM.LAST_UPDATER;

            Successful= uomManager.Save(productUOM);

            //保存产品照片数据
            String ids = null;
            ObjectTable ot = ViewState["DATA"] as ObjectTable;
            foreach(ObjectRow  row in ot)
            {
                PRODUCTPHOTO photo = row as PRODUCTPHOTO;
                if (photo.PHOTOID > 0)
                {
                    ids += photo.PHOTOID.ToString() + ",";
                }
            }
            if (ids != null && ids.Length > 1)
            {
                new PhotoManager().SaveProductPhoto(productUOM.PRODUCTID, ids, MyStateManager.DomainID);
            }
           
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
             Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change, this.MyStateManager.Name,
             this.MyStateManager.UserID, LogContent);
            return Successful;
        }
        catch (Exception ex)
        {
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                     Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
                     this.MyStateManager.UserID, "产品维护 - 异常:" + ex.Message);
            ShowMessage(ex.Message);
            return false;
        }
        return false;
    }

    private void BindPhoto()
    {
        var  ot = new PhotoManager().LoadImagesByProductID(id);
        if (ot != null)
        {
           
            for(int i=ot.Count;i<10;i++)
            {
                PRODUCTPHOTO photo = new PRODUCTPHOTO();
                int random1 = new Random().Next(1000, 9999);
                System.Threading.Thread.Sleep(10);
                int random2 = new Random().Next(1000, 9999);
                photo.ID = decimal.Parse(MyStateManager.PersonID + DateTime.Now.ToString("yyyyMMddHHmmss") + random1 + random2);
                photo.PRODUCTID = id;
                photo.PHOTOID = -1;
                photo.ACTIVE = true;
                photo.DOMAINID = MyStateManager.DomainID;
                photo.LAST_UPDATE_TIME = 0;
                photo.LAST_UPDATER = "";
                ot.Add(photo);
            }
            ViewState["DATA"] = ot;


        }
        dlPhotos.DataSource = ot;
        dlPhotos.DataBind();
        
    }

    protected void btnGoto_Click(object sender, EventArgs e)
    {
        int page = 0;
        try
        {
            page = int.Parse(txtPage.Text.Trim());
        }
        catch { page = 0; }
        if (page > 0 & page <= pages)
        {
            start_record = 1;
            end_record = pagesize;
            curpage = 1;

            for (int i = 1; i < page; i++)
            {
                start_record = end_record + 1;
                end_record = end_record + pagesize;
                curpage++;
            }

            txtInfo.Text = string.Format("总共<font color=blue>{0}</font>条记录&nbsp;&nbsp;共{1}页&nbsp;&nbsp;当前第{2}页", count, pages, curpage);
            BindFrom(start_record, end_record);

        }

    }

    public void BindFrom(decimal start, decimal end)
    {
        string where = "";
        if (ViewState["where"] != null)
            where = ViewState["where"].ToString();

        listPhoto.DataSource = PhotoManager.GetPhotoByPage(MyStateManager.DomainID, start, end, where);
        listPhoto.DataBind();
    }

    protected void IMAGE_DELETE(object sender, EventArgs e)
    {
        LinkButton btnDelete = (LinkButton)sender;
        ObjectTable ot = ViewState["DATA"] as ObjectTable;
        for (int i = 0; i < ot.Count; i++)
        {
            PRODUCTPHOTO photo = ot[i] as PRODUCTPHOTO;
            if (btnDelete.CommandArgument.Equals(photo.ID.ToString()))
            {
                photo.PHOTOID = -1;
                break;
            }
        }
        ViewState["DATA"] = ot;
        dlPhotos.DataSource = ot;
        dlPhotos.DataBind();
    }

    protected void dlPhotos_ItemDataBound(object sender, DataListItemEventArgs e)
    {
         PRODUCTPHOTO photo = e.Item.DataItem as PRODUCTPHOTO;
        if(photo != null && photo.PHOTOID == -1)
        {
            e.Item.FindControl("btnDelete").Visible = false;
        }
        
    }

    


    protected void btnPage_Click(object sender, EventArgs e)
    {
        Button btnPage = (Button)sender;
        if (btnPage.CommandName.Equals("FIRST"))
        {
            start_record = 1;
            end_record = pagesize;
            curpage = 1;
        }
        else if (btnPage.CommandName.Equals("PREVIOUS"))
        {
            if (curpage > 1)
            {
                end_record = start_record - 1;
                start_record = start_record - pagesize;
                curpage--;
            }
        }
        else if (btnPage.CommandName.Equals("NEXT"))
        {
            if (curpage < pages)
            {
                start_record = end_record + 1;
                end_record = end_record + pagesize;
                curpage++;
            }
        }
        else if (btnPage.CommandName.Equals("LAST"))
        {
            start_record = pagesize * (pages - 1)+1;
            if (start_record <= 0)
                start_record = 1;
            end_record = count;
            curpage++;
        }
        txtInfo.Text = string.Format("总共<font color=blue>{0}</font>条记录&nbsp;&nbsp;共{1}页&nbsp;&nbsp;当前第{2}页", count, pages, curpage);
        BindFrom(start_record, end_record);
    }

    protected void Select_Image(object sender, EventArgs e)
    {
        ImageButton btnImage = sender as ImageButton;
        if (btnImage.CommandArgument != null)
        {
            //查找该图片是否被使用过，被使用则不允许重复添加。
            ObjectTable ot = ViewState["DATA"] as ObjectTable;
            PRODUCTPHOTO FirstPhoto=null;
            for (int i = 0; i < ot.Count; i++)
            {
                PRODUCTPHOTO photo = ot[i] as PRODUCTPHOTO;
                if (FirstPhoto == null && photo.PHOTOID == -1)
                {
                    FirstPhoto = photo;
                }
                if (btnImage.CommandArgument.Equals(photo.PHOTOID.ToString()))
                {
                    ShowMessage("该图片已被选择，不能重复添加");
                    return;
                }
            }
            if (FirstPhoto !=  null)
            {
                FirstPhoto.PHOTOID = decimal.Parse(btnImage.CommandArgument);
                ViewState["DATA"] = ot;
                dlPhotos.DataSource = ot;
                dlPhotos.DataBind();
            }
        }
    }

 
   
    protected void gvPhotoList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        PhotoManager manager = new PhotoManager();
        PRODUCTPHOTO productPhoto = manager.LoadProductPhoto(e.Keys[0].ToString());
        if (productPhoto != null)
        {
            
            if(manager.DeleteProductPhoto(productPhoto.ID.ToString()))
                manager.DeletePhoto(productPhoto.PHOTOID.ToString());
        }
        BindPhoto();
    }
}
